<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
</head>
<body>
    <h1>axios的取消请求</h1>
    <button>执行加载</button>
    <button>取消加载</button>

    <script>
        // 获取上面按钮并绑定点击事件
        const bns = document.querySelectorAll("button");

        //1. 声明外部变量
        let cancel = null;

        // 执行请求的按钮事件
        bns[0].onclick = function(){
            console.log("执行Ajax请求");
            // 使用上面两个配置好的axios, 使用它们发送ajax
            axios({
                method: "get",
                url: "http://localhost:8080/api",
                //2. 配置对象添加 cancelToken 属性
                cancelToken: new axios.CancelToken(c => {
                    cancel = c;
                })
            })
            .then(v => {
                console.log("请求结束：", v.data);
            }).catch(e => {
                console.log("请求失败",e.message);
            });
        }


        // 取消请求的按钮事件
        bns[1].onclick = function(){
            if(cancel){
                cancel();
                cancel = null;
                console.log("取消请求！");
            }
        }
    </script>
</body>
</html>